//
//  Button.swift
//  BaseModule_Example
//
//  Created by seven on 2020/7/1.
//  Copyright © 2020 CocoaPods. All rights reserved.
//

import UIKit

public protocol TTUIButtonCompatible {
}

extension UIButton: TTUIButtonCompatible {
}

public extension TTUIButtonCompatible where Self: UIButton {
    /// 快速创建button
    static func withTitle(_ title: String?, titleColor tColor: UIColor?, backgroundColor bgColor: UIColor?, fontSize aSize: CGFloat, image img: UIImage?, frame f: CGRect) -> Self {
        let button = self.init(frame: f)
        if title != nil {
            button.tt_title(title)
        }
        if tColor != nil {
            button.setTitleColor(tColor, for: .normal)
        }
        if bgColor != nil {
            button.backgroundColor = bgColor
        }
        if aSize != 0 {
            button.titleLabel?.font = UIFont.systemFont(ofSize: aSize)
        }
        if img != nil {
            button.setImage(img, for: .normal)
        }
        return button
    }

    static func imageButton(_ image: UIImage?, frame f: CGRect) -> Self {
        let button = self.init(frame: f)
        button.setImage(image, for: .normal)
        return button
    }

    ///
    /// - Parameter text: String
    /// - Parameter state: UIControl.State
    /// - Returns: UIButton
    @discardableResult
    func tt_title(_ title: Any?, for state: UIControl.State? = .normal) -> Self {
        guard let title = title else {
            return self
        }
        if let state = state {
            setTitle("\(title)", for: state)
        } else {
            setTitle("\(title)", for: .normal)
        }
        return self
    }

    /// 设置按钮标题富文本
    ///
    /// - Parameter text: String
    /// - Returns: UIButton
    @discardableResult
    func tt_attributeTitle(_ title: NSMutableAttributedString?, for state: UIControl.State? = .normal) -> Self {
        if let state = state {
            setAttributedTitle(title, for: state)
        } else {
            setAttributedTitle(title, for: .normal)
        }
        return self
    }

    /// 设置按钮标题颜色
    ///
    /// - Parameter color: UIColor
    /// - Parameter state: UIControl.State
    /// - Returns: UIButton
    @discardableResult
    func tt_titleColor(_ color: UIColor?, for state: UIControl.State? = .normal) -> Self {
        setTitleColor(color, for: state ?? .normal)
        return self
    }

    /// 设置按钮图片
    ///
    /// - Parameter image: UIImage
    /// - Parameter state: UIControl.State
    /// - Returns: UIButton
    @discardableResult
    func tt_image(_ image: UIImage?, for state: UIControl.State? = .normal) -> Self {
        imageView?.contentMode = .scaleAspectFit
        if let state = state {
            setImage(image, for: state)
        } else {
            setImage(image, for: .normal)
        }
        return self
    }

    /// 设置按钮背景图片(用图片)
    ///
    /// - Parameter image: UIImage
    /// - Parameter state: UIControl.State
    /// - Returns: UIButton
    @discardableResult
    func tt_backgroundImage(_ image: UIImage?, for state: UIControl.State? = .normal) -> Self {
        if let state = state {
            setBackgroundImage(image, for: state)
        } else {
            setBackgroundImage(image, for: .normal)
        }
        return self
    }

    /// 设置按钮标题字体
    /// - Parameter font: 字体
    @discardableResult
    func tt_font(_ font: UIFont) -> Self {
        titleLabel?.font = font
        return self
    }

//    /// 加载网络图片
//    ///
//    /// - Parameter urlString: 图片链接地址
//    /// - Returns: UIImageView
//    @discardableResult
//    func tt_kingfisherImage(_ urlString: String?, placeholder: UIImage? = nil) -> Self {
//        self.kf.setImage(with: urlString?.tt_url, for: .normal, placeholder: placeholder)
//        self.kf.setImage(with: urlString?.tt_url, for: .highlighted, placeholder: placeholder)
//        return self
//    }
    func tt_countDown(_ time: Int, text: String, countingText: String, bgColor: UIColor, disabledBgColor: UIColor?, textColor: UIColor, disTextColor: UIColor) {
        var timeV = time
        let timer = DispatchSource.makeTimerSource()
        timer.schedule(wallDeadline: DispatchWallTime.now(), repeating: DispatchTimeInterval.seconds(1), leeway: DispatchTimeInterval.seconds(0))
        timer.setEventHandler {
            DispatchQueue.main.async {
                if self.superview == nil {
                    timer.cancel()
                    return
                }
            }
            if timeV <= 0 {
                timer.cancel()
                DispatchQueue.main.async {
                    self.backgroundColor = bgColor
                    self.tt_title(text)
                    self.tt_titleColor(textColor, for: .normal)
                    self.isUserInteractionEnabled = true
                }
            } else {
                DispatchQueue.main.async {
                    self.backgroundColor = disabledBgColor
                    self.tt_titleColor(disTextColor, for: .normal)
                    self.isUserInteractionEnabled = false
                    var str = ""
                    var countIng = countingText
                    if countIng.contains("%s") {
                        if let range = countIng.range(of: "%s") {
                            countIng.replaceSubrange(range, with: String(timeV))
                        }
                        str = countIng
                    } else {
                        str = "\(timeV)\(countingText)"
                    }
                    self.tt_title(str)
                }
            }
            timeV -= 1
        }
        timer.resume()
    }
}

public extension UIButton {
    var tt_font: CGFloat {
        set {
            titleLabel?.font = UIFont.systemFont(ofSize: fit(newValue))
        }
        get {
            titleLabel?.font?.pointSize ?? 0
        }
    }
}

// enum SSButtonStyle {
//    /// 默认圆角的按钮（圆角为4）
//    case `default`
//    /// 按钮颜色全部填充，且圆角为按钮高度的一半，会随着按钮大小的变化而变化
//    case filled(tintColor: UIColor?)
//    /// 按钮为透明，有边框颜色，且圆角为按钮高度的一半，会随着按钮大小的变化而变化
//    case border(tintColor: UIColor?)
// }
//
// enum SSButtonTintColorStrategy {
//    /// 让按钮的文字颜色自动跟随tintColor调整
//    case title
//    /// 让按钮的图片颜色自动跟随tintColor调整
//    case image
//    /// 让按钮的文字颜色和图片颜色自动跟随tintColor调整
//    case titleAndImage
// }
